import functools
import requests
import sys

sys.path.append("..")
import app


def request(*args, **kwargs):
    def decorator_repeat(func):
        params = kwargs

        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            respone = send_request(**params)
            return func(resp=respone, *args, **kwargs)

        return wrapper_repeat

    return decorator_repeat


def run(func):
    def wrapper_repeat():
        func()
    return wrapper_repeat


def send_request(method="get", url=None, header=None, param=None):
    resp = None
    if url is None:
        app.App().log.error("req请求参数错误")

    if method == 'get':
        if param is not None:
            url += '?'
            for key in param:
                url = url + str(key) + '=' + str(param[key]) + '&'
            # remove last '&'
            url = url[:-1]
        resp = requests.get(url, headers=header)
    elif method == 'post':
        resp = requests.post(url, headers=header, data=param)
    else:
        app.App().log.error("req请求参数错误")

    return resp
